package com.frostmourne.mxsguimaker.objects;

import com.frostmourne.mxsguimaker.MXSGuiMaker;
import me.clip.placeholderapi.PlaceholderAPI;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

public class JSEngine {

    private final ScriptEngine scriptEngine;

    public JSEngine() {
        scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    }

    public JSEngine putVariable(String name,Object obj){
        this.scriptEngine.put(name,obj);
        return this;
    }

    public Object invoke(String script,String name,Object... args){
        this.putVariable("classLoader", MXSGuiMaker.INSTANCE.getLoader());
        this.putVariable("scriptExpand", new ScriptExpand());
        this.putVariable("utils", new JSUtils());
        try {
            scriptEngine.eval(script);
            Invocable invocable = (Invocable) scriptEngine;
            if (args != null && args.length != 0){
                return invocable.invokeFunction(name,args);
            }else{
                return invocable.invokeFunction(name);
            }
        } catch (ScriptException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public void invoke(String script,String name){
        invoke(script,name,null,null);
    }

    public ScriptEngine getScriptEngine() {
        return scriptEngine;
    }
}
